<template>
  <div class="leave-container">
    <el-row :gutter="20">
      <!-- 左侧：请假申请表单 -->
      <el-col :span="16">
        <el-card class="leave-form-card">
          <template #header>
            <div class="card-header">
              <span>请假申请</span>
              <el-button type="primary" size="small" @click="showRenewDialog = true" :disabled="!hasActiveLeave">
                续假申请
              </el-button>
            </div>
          </template>

          <el-form :model="leaveForm" :rules="rules" ref="leaveFormRef" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="请假类型" prop="type">
                  <el-select v-model="leaveForm.type" placeholder="请选择请假类型" style="width: 100%">
                    <el-option label="病假" value="sick" />
                    <el-option label="事假" value="personal" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急程度" prop="urgency">
                  <el-select v-model="leaveForm.urgency" placeholder="请选择紧急程度" style="width: 100%">
                    <el-option label="一般" value="normal" />
                    <el-option label="紧急" value="urgent" />
                    <el-option label="非常紧急" value="critical" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="紧急联系人" prop="emergencyContact">
                  <el-input v-model="leaveForm.emergencyContact" placeholder="请输入紧急联系人姓名" maxlength="20"
                    show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="紧急联系电话" prop="emergencyPhone">
                  <el-input v-model="leaveForm.emergencyPhone" placeholder="请输入紧急联系电话" maxlength="11" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    v-model="leaveForm.startTime"
                    type="datetime"
                    placeholder="选择开始日期和时间"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    v-model="leaveForm.endTime"
                    type="datetime"
                    placeholder="选择结束日期和时间"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="请假去向" prop="locationType">
                  <el-select v-model="leaveForm.locationType" placeholder="请选择请假去向" style="width: 100%">
                    <el-option label="校内" value="campus" />
                    <el-option label="校外" value="off-campus" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" v-if="leaveForm.locationType === 'off-campus'">
              <el-col :span="24">
                <el-form-item label="校外地点" prop="location">
                  <el-input v-model="leaveForm.location" placeholder="请输入具体的外出地点" maxlength="100" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="请假原因" prop="reason">
              <el-input v-model="leaveForm.reason" type="textarea" :rows="4" placeholder="请详细说明请假原因" />
            </el-form-item>

            <el-form-item label="证明材料" prop="attachments">
              <el-upload ref="uploadRef" :file-list="fileList" :on-change="handleFileChange"
                :on-remove="handleFileRemove" :before-upload="beforeUpload" :auto-upload="false" multiple drag
                class="upload-demo">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png/pdf 文件，且不超过 10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitLeave" :loading="submitting">
                提交申请
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：请假记录和申请进度 -->
      <el-col :span="8">
        <el-card class="tabs-card">
          <!-- 详情视图 -->
          <div v-if="showDetailView && selectedLeaveDetail" class="detail-view">
            <div class="detail-header">
              <el-button type="primary" link @click="handleBackToList">
                <el-icon><ArrowLeft /></el-icon>
                返回
              </el-button>
            </div>
            
            <div class="detail-content-wrapper">
              <!-- 请假详情卡片 -->
              <div class="detail-info-card">
                <div class="info-row">
                  <span class="info-label">请假类型：</span>
                  <el-tag :type="getTypeColor(selectedLeaveDetail.type)" size="small">
                    {{ selectedLeaveDetail.type }}
                  </el-tag>
                </div>
                <div class="info-row">
                  <span class="info-label">请假日期：</span>
                  <span class="info-value">{{ selectedLeaveDetail.date || '—' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">请假时长：</span>
                  <span class="info-value">{{ selectedLeaveDetail.duration || '计算中...' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">请假原因：</span>
                  <span class="info-value">{{ selectedLeaveDetail.reason || '—' }}</span>
                </div>
                <div class="info-row" v-if="selectedLeaveDetail.emergencyContact">
                  <span class="info-label">紧急联系人：</span>
                  <span class="info-value">{{ selectedLeaveDetail.emergencyContact }}</span>
                </div>
                <div class="info-row" v-if="selectedLeaveDetail.location">
                  <span class="info-label">去向：</span>
                  <span class="info-value">{{ selectedLeaveDetail.location }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">当前状态：</span>
                  <el-tag :type="getStatusType(selectedLeaveDetail.status)" size="small">
                    {{ selectedLeaveDetail.status }}
                  </el-tag>
                </div>
                <div class="info-row" v-if="selectedLeaveDetail.headTeacherComment">
                  <span class="info-label">班主任评论：</span>
                  <span class="info-value">{{ selectedLeaveDetail.headTeacherComment }}</span>
                </div>
                <div class="info-row" v-if="selectedLeaveDetail.counselorComment">
                  <span class="info-label">辅导员评论：</span>
                  <span class="info-value">{{ selectedLeaveDetail.counselorComment }}</span>
                </div>
              </div>

              <!-- 审批进度 -->
              <div class="progress-section">
                <el-steps :active="getCurrentStep(selectedLeaveDetail)" direction="vertical" finish-status="success">
                  <el-step title="班主任审核" :description="getStepDescription(0, selectedLeaveDetail)"
                    :status="getStepStatus(0, selectedLeaveDetail)" />
                  <el-step title="辅导员审核" :description="getStepDescription(1, selectedLeaveDetail)"
                    :status="getStepStatus(1, selectedLeaveDetail)" />
                </el-steps>
              </div>
            </div>
          </div>

          <!-- 列表视图 -->
          <el-tabs v-else v-model="activeTab" type="border-card">
            <!-- 请假记录标签页 -->
            <el-tab-pane label="请假记录" name="history">
              <div class="tab-content">
                <!-- 查询筛选 -->
                <div class="filter-section">
                  <el-select v-model="filterType" placeholder="请选择请假类型筛选" clearable style="width: 100%"
                    @change="handleFilterChange">
                    <el-option label="全部" value="" />
                    <el-option label="病假" value="病假" />
                    <el-option label="事假" value="事假" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </div>

                <!-- 请假记录列表 -->
                <div class="leave-history-list">
                  <div 
                    v-for="(item, index) in filteredLeaveHistory" 
                    :key="index" 
                    class="leave-history-item"
                    @click="handleViewDetail(item)"
                  >
                    <div class="leave-item-header">
                      <div class="leave-type">
                        <el-tag :type="getTypeColor(item.type)" size="small">
                          {{ item.type }}
                        </el-tag>
                        <span class="leave-duration">{{ item.duration }}</span>
                      </div>
                      <div class="leave-actions">
                        <el-button 
                          v-if="(item.status === '待班主任审核' || item.status === '待辅导员审核') && item.status !== '已撤销' && !item.isCancelled" 
                          type="warning" 
                          size="small"
                          @click.stop="revokeLeave(item)"
                        >
                          撤销请假
                        </el-button>
                        <el-button 
                          v-if="item.status === '已批准' && !item.isCancelled" 
                          type="danger" 
                          size="small"
                          @click.stop="cancelLeave(item)"
                        >
                          销假
                        </el-button>
                      </div>
                    </div>

                    <div class="leave-item-content">
                      <p class="leave-reason">{{ item.reason }}</p>
                      <div class="leave-details">
                        <div class="detail-item" v-if="item.emergencyContact">
                          <span class="detail-label">紧急联系人：</span>
                          <span class="detail-value">{{ item.emergencyContact }}</span>
                        </div>
                        <div class="detail-item" v-if="item.location">
                          <span class="detail-label">去向：</span>
                          <span class="detail-value">{{ item.location }}</span>
                        </div>
                      </div>
                      <div class="leave-meta">
                        <span class="leave-date">{{ item.date }}</span>
                        <el-tag :type="getStatusType(item.status)" size="small">
                          {{ item.status }}
                        </el-tag>
                      </div>
                    </div>
                  </div>

                  <el-empty v-if="filteredLeaveHistory.length === 0" description="暂无请假记录" :image-size="80" />
                </div>
              </div>
            </el-tab-pane>

            <!-- 请假审核进度标签页 -->
            <el-tab-pane label="请假审核进度" name="progress">
              <div class="tab-content">
                <!-- 选择请假申请 -->
                <div class="progress-select-section">
                  <div class="select-label">选择请假申请</div>
                  <el-select v-model="selectedLeaveId" placeholder="请选择要查看的请假申请" style="width: 100%"
                    @change="handleLeaveSelectChange">
                    <el-option v-for="item in leaveHistory" :key="item.id"
                      :label="`${item.type} - ${item.date} - ${item.reason}`" :value="item.id" />
                  </el-select>
                </div>

                <!-- 申请信息展示 -->
                <div v-if="selectedLeave" class="selected-leave-info">
                  <div class="info-card">
                    <div class="info-row">
                      <span class="info-label">请假类型：</span>
                      <el-tag :type="getTypeColor(selectedLeave.type)" size="small">
                        {{ selectedLeave.type }}
                      </el-tag>
                    </div>
                    <div class="info-row">
                      <span class="info-label">请假日期：</span>
                      <span class="info-value">{{ selectedLeave.date }}</span>
                    </div>
                    <div class="info-row">
                      <span class="info-label">请假时长：</span>
                      <span class="info-value">{{ selectedLeave.duration }}</span>
                    </div>
                    <div class="info-row">
                      <span class="info-label">请假原因：</span>
                      <span class="info-value">{{ selectedLeave.reason }}</span>
                    </div>
                    <div class="info-row">
                      <span class="info-label">当前状态：</span>
                      <el-tag :type="getStatusType(selectedLeave.status)" size="small">
                        {{ selectedLeave.status }}
                      </el-tag>
                    </div>
                  </div>
                </div>

                <!-- 审核进度展示 -->
                <div v-if="selectedLeave" class="progress-section">
                  <el-steps :active="getCurrentStep(selectedLeave)" direction="vertical" finish-status="success">
                    <el-step title="班主任审核" :description="getStepDescription(0, selectedLeave)"
                      :status="getStepStatus(0, selectedLeave)" />
                    <el-step title="辅导员审核" :description="getStepDescription(1, selectedLeave)"
                      :status="getStepStatus(1, selectedLeave)" />
                  </el-steps>
                </div>

                <!-- 空状态 -->
                <el-empty v-else description="请先选择一个请假申请查看审核进度" :image-size="80" style="padding: 40px 0;" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 撤销请假对话框 -->
    <el-dialog v-model="showRevokeDialog" title="撤销请假" width="500px" @close="handleRevokeClose">
      <el-form :model="revokeForm" :rules="revokeRules" ref="revokeFormRef" label-width="100px">
        <el-form-item label="撤销理由" prop="comment">
          <el-input 
            v-model="revokeForm.comment" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入撤销理由" 
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRevokeDialog = false">取消</el-button>
        <el-button type="warning" :loading="revoking" @click="handleConfirmRevoke">确定撤销</el-button>
      </template>
    </el-dialog>

    <!-- 续假对话框 -->
    <el-dialog v-model="showRenewDialog" title="续假申请" width="600px" :before-close="handleRenewClose">
      <el-form :model="renewForm" :rules="renewRules" ref="renewFormRef" label-width="100px">
        <el-form-item label="原请假结束时间">
          <el-date-picker v-model="originalEndTime" type="datetime" disabled style="width: 100%" />
        </el-form-item>

        <el-form-item label="新的结束时间" prop="newEndTime">
          <el-date-picker v-model="renewForm.newEndTime" type="datetime" placeholder="选择新的结束时间" style="width: 100%" />
        </el-form-item>

        <el-form-item label="续假原因" prop="reason">
          <el-input v-model="renewForm.reason" type="textarea" :rows="3" placeholder="请说明续假原因" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showRenewDialog = false">取消</el-button>
        <el-button type="primary" @click="submitRenew" :loading="submitting">
          提交续假申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile, type UploadFiles } from 'element-plus'
import { UploadFilled, ArrowLeft } from '@element-plus/icons-vue'
import { submitLeave as submitLeaveApi, getLeaveListByStudentId, revokeLeave as revokeLeaveApi, returnLeave as returnLeaveApi, type LeaveRequest, type LeaveListItem, type RevokeLeaveRequest } from '../../api/leave'
import { getStudentById } from '../../api/studentInfo'

const leaveFormRef = ref<FormInstance>()
const renewFormRef = ref<FormInstance>()
const uploadRef = ref()

// 表单数据
const leaveForm = reactive({
  type: '',
  urgency: 'normal',
  emergencyContact: '',
  emergencyPhone: '',
  startTime: '',
  endTime: '',
  locationType: '',
  location: '',
  reason: '',
  attachments: [] as string[]
})

const renewForm = reactive({
  newEndTime: '',
  reason: ''
})

// 文件上传相关
const fileList = ref<UploadFile[]>([])
const submitting = ref(false)

// 撤销请假相关
const showRevokeDialog = ref(false)
const revoking = ref(false)
const revokeFormRef = ref<FormInstance>()
const currentRevokeItem = ref<any>(null)
const revokeForm = reactive({
  comment: ''
})

// 续假相关
const showRenewDialog = ref(false)
const originalEndTime = ref(new Date())

// 标签页相关
const activeTab = ref('history')

// 查询筛选相关
const filterType = ref('')

// 请假审核进度相关
const selectedLeaveId = ref<number | null>(null)

// 详情视图相关
const showDetailView = ref(false)
const selectedLeaveDetail = ref<any>(null)

// 表单验证规则
const rules: FormRules = {
  type: [
    { required: true, message: '请选择请假类型', trigger: 'change' }
  ],
  urgency: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ],
  emergencyContact: [
    { required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }
  ],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  locationType: [
    { required: true, message: '请选择请假去向', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (_rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        if (!leaveForm.startTime) {
          callback()
          return
        }
        const start = new Date(leaveForm.startTime)
        const end = new Date(value)
        if (end <= start) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  location: [
    {
      required: true,
      message: '请输入校外地点',
      trigger: 'blur',
      validator: (_rule, value, callback) => {
        if (leaveForm.locationType === 'off-campus' && !value) {
          callback(new Error('请输入校外地点'))
        } else {
          callback()
        }
      }
    }
  ],
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' }
  ]
}

const renewRules: FormRules = {
  newEndTime: [
    { required: true, message: '请选择新的结束时间', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入续假原因', trigger: 'blur' }
  ]
}

const revokeRules: FormRules = {
  comment: [
    { required: true, message: '请输入撤销理由', trigger: 'blur' }
  ]
}

// 请假记录数据
const leaveHistory = ref<any[]>([])

// 计算属性
const hasActiveLeave = computed(() => {
  return leaveHistory.value.some(item =>
    item.status === '已批准' && !item.isCancelled
  )
})

// 过滤后的请假记录
const filteredLeaveHistory = computed(() => {
  if (!filterType.value) {
    return leaveHistory.value
  }
  return leaveHistory.value.filter(item => item.type === filterType.value)
})

// 选中的请假申请
const selectedLeave = computed(() => {
  if (!selectedLeaveId.value) return null
  return leaveHistory.value.find(item => item.id === selectedLeaveId.value) || null
})

// 工具函数
const getStatusType = (status: string) => {
  switch (status) {
    case '已批准': return 'success'
    case '待审核': return 'warning'
    case '待班主任审核': return 'warning'
    case '待辅导员审核': return 'warning'
    case '已拒绝': return 'danger'
    case '已撤销': return 'info'
    case '已销假': return 'info'
    default: return 'info'
  }
}

const getTypeColor = (type: string) => {
  switch (type) {
    case '病假': return 'danger'
    case '事假': return 'warning'
    case '其他': return 'info'
    default: return ''
  }
}

// 获取当前步骤（基于 approvalStatus）
const getCurrentStep = (leave: any) => {
  if (!leave) return 0

  const approvalStatus = leave.approvalStatus
  if (approvalStatus === undefined || approvalStatus === null) {
    // 如果没有 approvalStatus，使用旧的 progress 逻辑作为后备
    const progress = leave.progress
    if (progress && progress.counselor && progress.counselor.status === 'approved') return 2
    if (progress && progress.teacher && progress.teacher.status === 'approved') return 1
    return 0
  }

  // 根据 approvalStatus 判断当前步骤
  // 1: 待班主任审批 -> 步骤0进行中
  // 2: 待辅导员审批（班主任已通过）-> 步骤1进行中
  // 4: 审批通过 -> 步骤2（完成）
  // 5: 审批驳回 -> 显示在驳回的步骤（通常是在班主任阶段被驳回）
  if (approvalStatus === 1) {
    return 0 // 班主任审核中
  } else if (approvalStatus === 2) {
    return 1 // 辅导员审核中
  } else if (approvalStatus === 4) {
    return 2 // 全部完成
  } else if (approvalStatus === 5) {
    // 审批驳回：通常是在班主任阶段被驳回，所以返回 0
    // 如果后续 API 提供了更详细的驳回阶段信息，可以再优化
    return 0 // 显示在第一步（班主任审核阶段）
  }
  return 0
}

const getStepStatus = (step: number, leave?: any) => {
  const activeLeave = leave || selectedLeave.value
  if (!activeLeave) return 'wait'

  const approvalStatus = activeLeave.approvalStatus

  // 如果有 approvalStatus，使用新的逻辑
  if (approvalStatus !== undefined && approvalStatus !== null) {
    switch (step) {
      case 0: // 班主任审核
        if (approvalStatus === 1) {
          return 'process' // 待班主任审批，进行中
        } else if (approvalStatus === 2 || approvalStatus === 4) {
          return 'success' // 班主任已通过（进入辅导员阶段或全部完成）
        } else if (approvalStatus === 5) {
          // 审批驳回：由于无法判断是在哪个阶段被驳回的，默认显示为班主任驳回
          // 如果后续 API 提供了更详细的驳回信息，可以再优化
          return 'error'
        }
        return 'wait'
      case 1: // 辅导员审核
        if (approvalStatus === 2) {
          return 'process' // 待辅导员审批，进行中（班主任已通过）
        } else if (approvalStatus === 4) {
          return 'success' // 辅导员已通过，全部完成
        } else if (approvalStatus === 5) {
          // 审批驳回：如果 approvalStatus = 5，通常是班主任阶段被驳回
          // 辅导员还未审核，所以显示为 wait（等待状态）
          // 如果后续 API 提供了更详细的驳回信息（如驳回阶段），可以再优化
          return 'wait'
        } else if (approvalStatus === 1) {
          return 'wait' // 班主任还没审核，辅导员等待
        }
        return 'wait'
      default:
        return 'wait'
    }
  }

  // 后备逻辑：使用旧的 progress 结构
  const progress = activeLeave.progress
  if (!progress) return 'wait'

  switch (step) {
    case 0:
      return progress.teacher?.status === 'approved' ? 'success' :
        progress.teacher?.status === 'rejected' ? 'error' : 'process'
    case 1:
      return progress.counselor?.status === 'approved' ? 'success' :
        progress.counselor?.status === 'rejected' ? 'error' :
          progress.teacher?.status === 'approved' ? 'process' : 'wait'
    default:
      return 'wait'
  }
}

const getStepDescription = (step: number, leave?: any) => {
  const activeLeave = leave || selectedLeave.value
  if (!activeLeave) return '暂无申请'

  const approvalStatus = activeLeave.approvalStatus

  // 如果有 approvalStatus，使用新的逻辑
  if (approvalStatus !== undefined && approvalStatus !== null) {
    switch (step) {
      case 0: // 班主任审核
        if (approvalStatus === 1) {
          return '等待审核'
        } else if (approvalStatus === 2 || approvalStatus === 4) {
          return '审核通过'
        } else if (approvalStatus === 5) {
          return '审核驳回'
        }
        return '等待审核'
      case 1: // 辅导员审核
        if (approvalStatus === 2) {
          return '等待审核'
        } else if (approvalStatus === 4) {
          return '审核通过'
        } else if (approvalStatus === 5) {
          return '审核驳回'
        } else if (approvalStatus === 1) {
          return '等待审核'
        }
        return '等待审核'
      default:
        return ''
    }
  }

  // 后备逻辑：使用旧的 progress 结构
  const progress = activeLeave.progress
  if (!progress) return '等待审核'

  switch (step) {
    case 0:
      return progress.teacher?.time || '等待审核'
    case 1:
      return progress.counselor?.time || '等待审核'
    default:
      return ''
  }
}

// 处理筛选变化
const handleFilterChange = () => {
  // 筛选逻辑已在计算属性中处理
}

// 处理请假申请选择变化
const handleLeaveSelectChange = (leaveId: number) => {
  selectedLeaveId.value = leaveId
}

// 查看请假详情
const handleViewDetail = (item: any) => {
  selectedLeaveDetail.value = item
  showDetailView.value = true
}

// 返回列表
const handleBackToList = () => {
  showDetailView.value = false
  selectedLeaveDetail.value = null
}

// 文件上传处理
const handleFileChange = (_file: UploadFile, files: UploadFiles) => {
  fileList.value = files
}

const handleFileRemove = (_file: UploadFile, files: UploadFiles) => {
  fileList.value = files
}

const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isValidSize = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF 格式的文件!')
    return false
  }
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 提交请假申请
const submitLeave = async () => {
  if (!leaveFormRef.value) return

  await leaveFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 获取登录时存储的用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (!userInfoStr) {
          ElMessage.error('请先登录')
          submitting.value = false
          return
        }

        const userInfo = JSON.parse(userInfoStr)
        const userId = userInfo.userId

        if (!userId) {
          ElMessage.error('无法获取用户ID，请重新登录')
          submitting.value = false
          return
        }

        // 调用学生信息接口获取学生信息，获取 id
        const studentInfoRes = await getStudentById(Number(userId))
        const studentInfoCode = String(studentInfoRes.code)
        if ((studentInfoCode !== '200' && studentInfoCode !== '0') || !studentInfoRes.data) {
          ElMessage.error(studentInfoRes.msg || '获取学生信息失败，请重试')
          submitting.value = false
          return
        }

        const studentId = studentInfoRes.data.id

        // 验证 id 是否存在
        if (!studentId && studentId !== 0) {
          ElMessage.error('无法获取学生ID，请检查学生信息是否完整')
          submitting.value = false
          return
        }

        const finalStudentId = typeof studentId === 'string' ? studentId : String(studentId)

        // 转换请假类型：sick -> 1(病假), personal -> 2(事假), other -> 2(事假，因为API只有1和2)
        let leaveType = 2 // 默认为事假
        if (leaveForm.type === 'sick') {
          leaveType = 1 // 病假
        } else if (leaveForm.type === 'personal') {
          leaveType = 2 // 事假
        } else {
          leaveType = 2 // 其他类型也作为事假处理
        }
        const urgencyLevel = leaveForm.urgency === 'normal' ? 1 : 2
        const destinationType = leaveForm.locationType === 'campus' ? 1 : 2
        
        // 将日期时间转换为 ISO 8601 格式
        // value-format="YYYY-MM-DD HH:mm:ss" 返回格式: "2025-11-08 08:59:42" (本地时间)
        // 需要转换为 ISO 8601 格式: "2025-11-08T08:59:42.000Z" (UTC 时间)
        const convertToISO = (dateTimeStr: string): string => {
          if (!dateTimeStr) return ''
          // 将 "YYYY-MM-DD HH:mm:ss" 格式的字符串转换为 Date 对象
          // 使用 Date 构造函数解析本地时间，然后转换为 UTC 的 ISO 字符串
          // 格式: "2025-11-08 08:59:42" -> Date 对象 -> ISO 字符串
          const parts = dateTimeStr.split(' ')
          if (parts.length !== 2) {
            // 如果格式不正确，尝试使用 Date 构造函数直接解析
            return new Date(dateTimeStr).toISOString()
          }
          
          const [datePart, timePart] = parts
          if (!datePart || !timePart) {
            return new Date(dateTimeStr).toISOString()
          }
          
          const dateParts = datePart.split('-').map(Number)
          const timeParts = timePart.split(':').map(Number)
          
          if (dateParts.length < 3 || timeParts.length < 2) {
            return new Date(dateTimeStr).toISOString()
          }
          
          const [year, month, day] = dateParts
          const [hour, minute, second] = timeParts
          
          // 创建本地时间的 Date 对象
          const localDate = new Date(
            year || 0,
            (month || 1) - 1,
            day || 1,
            hour || 0,
            minute || 0,
            second || 0
          )
          
          // 转换为 ISO 8601 格式 (UTC)
          return localDate.toISOString()
        }
        
        let startTimeISO = ''
        let endTimeISO = ''
        if (leaveForm.startTime) {
          startTimeISO = convertToISO(leaveForm.startTime)
        }
        if (leaveForm.endTime) {
          endTimeISO = convertToISO(leaveForm.endTime)
        }

        const requestData: LeaveRequest = {
          studentId: finalStudentId,
          leaveType: leaveType,
          urgencyLevel: urgencyLevel,
          destinationType: destinationType,
          emergencyContact: leaveForm.emergencyContact.trim(),
          emergencyPhone: leaveForm.emergencyPhone.trim(),
          proofMaterialUrl: 'string',
          reason: leaveForm.reason.trim(),
          startTime: startTimeISO,
          endTime: endTimeISO
        } as LeaveRequest

        // 如果是校外，添加校外地址（必填，放在最后）
        if (destinationType === 2) {
          if (!leaveForm.location || !leaveForm.location.trim()) {
            ElMessage.error('校外请假必须填写校外详细去向')
            submitting.value = false
            return
          }
          requestData.offCampusAddress = leaveForm.location.trim()
        }

        // 调用API提交请假申请
        const response = await submitLeaveApi(requestData)

        const responseCode = String(response.code)
        if (responseCode === '200' || responseCode === '0') {
          // 添加到请假记录
          const newLeave = {
            id: response.data?.id || Date.now(),
            date: new Date().toISOString().split('T')[0] as string,
            type: leaveForm.type === 'sick' ? '病假' : leaveForm.type === 'personal' ? '事假' : '其他',
            reason: leaveForm.reason,
            emergencyContact: leaveForm.emergencyContact,
            location: leaveForm.locationType === 'campus' ? '校内' : leaveForm.location,
            status: '待班主任审核', // 新提交的申请，状态为待班主任审核
            duration: '计算中...',
            isCancelled: false,
            approvalStatus: 1, // 新提交的申请，状态为待班主任审批
            progress: {
              teacher: { status: 'pending', time: '' },
              counselor: { status: 'waiting', time: '' },
              college: { status: 'waiting', time: '' }
            }
          }

          leaveHistory.value.unshift(newLeave)
          ElMessage.success('请假申请提交成功')
          resetForm()
        } else {
          ElMessage.error(response.msg || '提交失败，请重试')
        }
      } catch (error: any) {
        const errorMessage = error.message || '提交失败，请重试'
        ElMessage.error(errorMessage)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!leaveFormRef.value) return
  leaveFormRef.value.resetFields()
  fileList.value = []
}

// 撤销请假功能
const revokeLeave = (item: any) => {
  currentRevokeItem.value = item
  revokeForm.comment = ''
  showRevokeDialog.value = true
}

// 确认撤销请假
const handleConfirmRevoke = async () => {
  if (!revokeFormRef.value) return
  
  await revokeFormRef.value.validate(async (valid) => {
    if (valid && currentRevokeItem.value) {
      revoking.value = true
      try {
        const leaveId = currentRevokeItem.value.id
        if (!leaveId) {
          ElMessage.error('无法获取请假ID')
          revoking.value = false
          return
        }

        const revokeData: RevokeLeaveRequest = {
          leaveId: leaveId,
          comment: revokeForm.comment.trim()
        }

        const response = await revokeLeaveApi(revokeData)
        const responseCode = String(response.code)

        if (responseCode === '200' || responseCode === '0') {
          ElMessage.success('撤销成功')
          showRevokeDialog.value = false
          
          // 如果当前查看的是被撤销的请假详情，返回列表
          if (showDetailView.value && selectedLeaveDetail.value && selectedLeaveDetail.value.id === leaveId) {
            handleBackToList()
          }
          
          // 刷新列表以确保数据同步
          await fetchLeaveList()
        } else {
          ElMessage.error(response.msg || '撤销失败，请重试')
        }
      } catch (error: any) {
        console.error('撤销请假失败:', error)
        ElMessage.error(error.message || '撤销失败，请稍后重试')
      } finally {
        revoking.value = false
      }
    }
  })
}

// 关闭撤销对话框
const handleRevokeClose = () => {
  revokeFormRef.value?.resetFields()
  revokeForm.comment = ''
  currentRevokeItem.value = null
}

// 销假功能
const cancelLeave = async (item: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要销假吗？此操作不可撤销。',
      '销假确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const leaveId = item.id
    if (!leaveId) {
      ElMessage.error('无法获取请假ID')
      return
    }

    // 调用销假接口
    const response = await returnLeaveApi(leaveId)
    const responseCode = String(response.code)

    if (responseCode === '200' || responseCode === '0') {
      ElMessage.success('销假成功')
      
      // 更新本地状态
      item.isCancelled = true
      item.status = '已销假'
      item.approvalStatus = 6 // 已销假状态
      
      // 如果当前查看的是被销假的请假详情，返回列表
      if (showDetailView.value && selectedLeaveDetail.value && selectedLeaveDetail.value.id === leaveId) {
        handleBackToList()
      }
      
      // 刷新列表以确保数据同步
      await fetchLeaveList()
    } else {
      ElMessage.error(response.msg || '销假失败，请重试')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('销假失败:', error)
      ElMessage.error(error.message || '销假失败，请稍后重试')
    }
  }
}

// 续假相关
const handleRenewClose = () => {
  showRenewDialog.value = false
  renewForm.newEndTime = ''
  renewForm.reason = ''
}

const submitRenew = async () => {
  if (!renewFormRef.value) return

  await renewFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 模拟提交续假申请
        await new Promise(resolve => setTimeout(resolve, 1000))

        ElMessage.success('续假申请提交成功')
        handleRenewClose()
      } catch (error) {
        ElMessage.error('提交失败，请重试')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 获取学生请假申请列表
const fetchLeaveList = async () => {
  try {
    // 获取登录时存储的用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const userId = userInfo.userId

    if (!userId) {
      return
    }

    // 调用学生信息接口获取学生信息，获取 id
    const studentInfoRes = await getStudentById(Number(userId))
    const studentInfoCode = String(studentInfoRes.code)
    if ((studentInfoCode !== '200' && studentInfoCode !== '0') || !studentInfoRes.data) {
      return
    }

    // 获取学生ID
    const studentId = studentInfoRes.data.id
    if (!studentId && studentId !== 0) {
      return
    }

    // 调用获取请假申请列表接口，使用 id
    const response = await getLeaveListByStudentId(studentId)
    const responseCode = String(response.code)

    if (responseCode === '200' || responseCode === '0') {
      const leaveList = response.data || []

      // 将接口返回的数据映射到 leaveHistory
      leaveHistory.value = leaveList.map((item: LeaveListItem) => {
        // 转换请假类型：1 -> 病假, 2 -> 事假
        let typeText = '其他'
        if (item.leaveType === 1) {
          typeText = '病假'
        } else if (item.leaveType === 2) {
          typeText = '事假'
        }

        // 转换状态：根据 approvalStatus 进行转换
        let statusText = '待审核'
        // 优先使用 approvalStatus 来判断状态
        if (item.approvalStatus !== undefined && item.approvalStatus !== null) {
          if (item.approvalStatus === 1) {
            statusText = '待班主任审核' // 待班主任审批
          } else if (item.approvalStatus === 2) {
            statusText = '待辅导员审核' // 班主任已通过，待辅导员审批
          } else if (item.approvalStatus === 3) {
            statusText = '已撤销' // 已撤销
          } else if (item.approvalStatus === 4) {
            statusText = '已批准' // 审批通过
          } else if (item.approvalStatus === 5) {
            statusText = '已拒绝' // 审批驳回
          } else if (item.approvalStatus === 6) {
            statusText = '已销假' // 已销假
          } else {
            statusText = '待审核'
          }
        } else if (typeof item.status === 'number') {
          statusText = '待审核'
        } else if (typeof item.status === 'string') {
          statusText = item.status
        }

        // 计算请假时长
        let duration = '计算中...'
        if (item.startTime && item.endTime) {
          try {
            const start = new Date(item.startTime)
            const end = new Date(item.endTime)
            const diffTime = end.getTime() - start.getTime()
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
            duration = `${diffDays}天`
          } catch (e) {
            duration = '计算中...'
          }
        }

        // 格式化日期
        let dateText = ''
        if (item.startTime) {
          try {
            const date = new Date(item.startTime)
            dateText = date.toISOString().split('T')[0] || ''
          } catch (e) {
            dateText = ''
          }
        }

        // 转换去向
        let locationText = ''
        if (item.destinationType === 1) {
          locationText = '校内'
        } else if (item.destinationType === 2) {
          locationText = item.offCampusAddress || '校外'
        }

        return {
          id: item.id || Date.now(),
          date: dateText,
          type: typeText,
          reason: item.reason || '',
          emergencyContact: item.emergencyContact || '',
          location: locationText,
          status: statusText,
          duration: duration,
          isCancelled: false,
          approvalStatus: item.approvalStatus !== undefined ? item.approvalStatus : 0, // 保存审批状态
          headTeacherComment: item.headTeacherComment || null, // 班主任评论
          counselorComment: item.counselorComment || null, // 辅导员评论
          progress: {
            teacher: { status: 'pending', time: '' },
            counselor: { status: 'waiting', time: '' },
            college: { status: 'waiting', time: '' }
          }
        }
      })
    }
  } catch (error) {
    // 静默失败，不影响页面正常显示
  }
}

// 页面加载时获取请假申请列表
onMounted(() => {
  fetchLeaveList()
})
</script>

<style scoped>
.leave-container {
  padding: 0;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 请假表单卡片 */
.leave-form-card {
  height: fit-content;
}

/* 标签页卡片 */
.tabs-card {
  height: calc(100vh - 160px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tabs-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tabs-card :deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tabs-card :deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.tabs-card :deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tab-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 16px;
}

/* 请假记录列表 */
.leave-history-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.leave-history-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  background: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.leave-history-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
  border-color: #409eff;
  background: #f0f9ff;
}

.leave-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.leave-type {
  display: flex;
  align-items: center;
  gap: 8px;
}

.leave-duration {
  font-size: 12px;
  color: #909399;
  background: #f0f0f0;
  padding: 2px 8px;
  border-radius: 4px;
}

.leave-actions {
  display: flex;
  gap: 8px;
}

.leave-item-content {
  margin-top: 8px;
}

.leave-reason {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.leave-details {
  margin: 8px 0;
  padding: 8px 0;
  border-top: 1px solid #f0f0f0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #909399;
  margin-right: 8px;
  min-width: 80px;
}

.detail-value {
  color: #606266;
  font-weight: 500;
}

.leave-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.leave-date {
  font-size: 12px;
  color: #909399;
}

/* 请假审核进度相关样式 */
.progress-select-section {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.select-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.selected-leave-info {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.info-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  color: #909399;
  margin-right: 8px;
  min-width: 80px;
}

.info-value {
  color: #606266;
  font-weight: 500;
  flex: 1;
}

.progress-section {
  margin-top: 20px;
  padding: 0 10px;
  flex-shrink: 0;
}

/* 详情视图样式 */
.detail-view {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.detail-content-wrapper {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.detail-info-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  margin-bottom: 20px;
}

.detail-info-card .info-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 1.6;
}

.detail-info-card .info-row:last-child {
  margin-bottom: 0;
}

.detail-info-card .info-label {
  color: #909399;
  margin-right: 12px;
  min-width: 100px;
  font-weight: 500;
}

.detail-info-card .info-value {
  color: #606266;
  flex: 1;
  word-break: break-word;
}

.detail-view .progress-section {
  margin-top: 0;
  padding: 20px 0;
}

/* 文件上传样式 */
.upload-demo {
  width: 100%;
}

.upload-demo :deep(.el-upload-dragger) {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.upload-demo :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

.upload-demo :deep(.el-upload-dragger .el-icon--upload) {
  font-size: 28px;
  color: #8c939d;
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  margin: 0 auto 16px;
}

.upload-demo :deep(.el-upload__text) {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-demo :deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

.upload-demo :deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  text-align: center;
  margin-top: 8px;
}

/* 续假对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

/* 步骤条样式 */
:deep(.el-steps--vertical) {
  padding: 0 20px;
}

:deep(.el-step__title) {
  font-size: 14px;
  font-weight: 600;
}

:deep(.el-step__description) {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .leave-container .el-col {
    margin-bottom: 20px;
  }

  .leave-item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .leave-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

/* 加载状态 */
.el-button.is-loading {
  pointer-events: none;
}

/* 表单验证错误样式 */
:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c inset;
}

:deep(.el-form-item.is-error .el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #f56c6c inset;
}

/* 标签颜色 */
.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #f5dab1;
  color: #e6a23c;
}

.el-tag--info {
  background-color: #f4f4f5;
  border-color: #d3d4d6;
  color: #909399;
}

.el-tag--success {
  background-color: #f0f9ff;
  border-color: #b3e19d;
  color: #67c23a;
}
</style>
